package com.jk1123.dotdog.server;

import com.jk1123.dotdog.http.*;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class SocketProcessor implements Runnable {
    private ServletContainer servletContainer;
    private Socket socket;

    public SocketProcessor(ServletContainer servletContainer, Socket socket) {
        this.servletContainer = servletContainer;
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            InputStream in = socket.getInputStream();
            OutputStream out = socket.getOutputStream();
            HttpServletRequest request=wrapperRequest(in);
            HttpServletResponse response=wrapperResponse(out);

            Servlet servlet = servletContainer.getServlet(request.getRequestURI());

            servlet.service(request,response);
            out.close();
            in.close();


        } catch (Throwable e) {
            e.printStackTrace();

        }
    }

    private HttpServletResponse wrapperResponse(OutputStream out) {
        return new HttpServletResponseImpl(out);
    }

    private HttpServletRequest wrapperRequest(InputStream in) {

        return new HttpServletRequestImpl(in);
    }
}
